package Stock;

import java.util.Stack;

/**
 * @Classname JZ31栈的压入弹出序列
 * @Description TODO
 * @Date 2022/12/6 23:34
 * @Created by xjl
 */
public class JZ31栈的压入弹出序列 {

    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> stack = new Stack<>();
        int i=0;
        for (int num:pushed){
            // 压栈
            stack.add(num);
            while (!stack.isEmpty()&&stack.peek()==popped[i]){
                // 出栈
                stack.pop();
                i++;
            }
        }
        // 判断是否空 如果是空 表示的是顺序是对的 否则顺序不符要求。
        return stack.isEmpty();
    }

    public boolean validateStackSequences2(int[] pushed, int[] popped) {

        Stack<Integer> stack=new Stack<>();
        int index=0;
        for (int i:pushed){
            stack.add(i);
            while (!stack.isEmpty()&&stack.peek()==popped[index]){
                stack.pop();
                index++;
            }
        }
        return stack.isEmpty();
    }
}
